package com.hujiang.basic.search.common.component;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.reindex.ReindexPlugin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import lombok.extern.slf4j.Slf4j;

@Configuration
@Slf4j
@ComponentScan("com.hujiang.basic.search.common.converter")
public class ElasticSearchConfig {

    @Value("${elasticsearch.connection}")
    private String connectionString;

    @Value("${elasticsearch.clustername}")
    private String clusterName;

    @Bean(name = "elasticSearchClient")
    public Client client() {
        Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName)
                .put("client.transport.ping_timeout", "30s")
                .put("client.transport.sniff", false).build();

        TransportClient client = TransportClient.builder().addPlugin(ReindexPlugin.class).settings(settings).build();
        String[] connections = StringUtils.split(connectionString, ",");
        try {
            for (String connection : connections) {
                String[] hostAndPort = StringUtils.split(connection, ":");
                client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostAndPort[0]),
                        NumberUtils.toInt(hostAndPort[1])));
            }
        } catch (UnknownHostException e) {
            log.error("ElasticSearchConfig parse connection ", e);
        }

        return client;
    }

    @Bean(name = "hJElasticSearchClient")
    public HJElasticSearchClient HJElasticSearchClient() {
        return new HJElasticSearchClient(client());
    }

}
